package com.hliushi.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName MySecurity
 * @Description TODO
 * @Author hliushi
 * @Date 2021/7/15 23:10
 * @Version V1.0
 **/
// @EnableWebSecurity
public class MySecurity extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 定制请求的授权规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");


        // 提供一个默认表单, 如果访问的资源权限不够, 会自动跳转到security自带的登录页面
        http.formLogin().loginProcessingUrl("/");

        // 开启记住我功能
        http.rememberMe();
    }


    // 定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user01")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2")
                .and()
                .withUser("user02")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3")
                .and()
                .withUser("user03")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP3");


        auth.inMemoryAuthentication().
                passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user_test")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("VIP1", "VIP2", "VIP3");
    }
}
